<template>
	<view class="container">
		<view class="content">
			<image :src="avatar" class="img-show" v-show="avatar" />
			<view class="avatar" v-show="!avatar">
				<image src="../../static/images/avatar.png" class="img" />
				<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar"></button>
			</view>

			<input type="nickname" maxlength="10" class="name" v-model="nickname" placeholder="请输入昵称" />
			<view class="submit btn" @click="submit">保存</view>
		</view>
	</view>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { state } from '../../store/user';
import getUser from '../../vendor/user';
const { update } = getUser();
const avatar = ref(state.avatar);
const nickname = ref(state.nickname);
const onChooseAvatar = (e) => {
	const fileName = new Date().getMilliseconds() + '.jpg';
	uniCloud.uploadFile({
		filePath: e.detail.avatarUrl,
		cloudPath: fileName,
		success(res) {
			avatar.value = res.fileID;
		},
		fail() {
			uni.showToast({
				title: '图片上传失败',
				icon: 'error'
			});
		},
		complete() {}
	});

	// avatar.value = e.detail.avatarUrl;
	
};

const submit = () => {
	if (nickname.value) {
		state.nickname = nickname.value;
	}
	if (avatar.value) {
		state.avatar = avatar.value;
	}

	// 接口保存信息

	update(state);

	uni.navigateBack();
};
</script>

<style scoped lang="scss">
.container {
	height: 100vh;
	display: flex;
	flex-direction: column;
	justify-content: center;
}
.content {
	width: 150px;
	text-align: center;
	margin: 0 auto;
}
.img-show {
	width: 100px;
	height: 100px;
	border-radius: 8px;
}
.avatar {
	position: relative;
	width: 100px;
	height: 100px;

	text-align: center;
	margin: 0 auto;

	border-radius: 8px;
	background: #b7b7b7;

	.img {
		width: 50px;
		height: 50px;
		margin: 22px 0;
	}
	.avatar-wrapper {
		width: 100%;
		position: absolute;
		height: 100px;
		left: 0;
		top: 0;
		z-index: 2;
		background: transparent !important;

		&::after {
			border: 0;
		}
	}
}
.btn {
	text-align: center;
	color: white;
	line-height: 40px;
	width: 110px;
	border-radius: $uni-border-radius-lg;
	background: #a5d63f;
	margin: 80px auto;
}
.name {
	margin-top: 20px;
}
</style>
